<template>
  <div ref="container" class="auto-tooltip-container">
    <el-tooltip :disabled="!showTooltip" :content="data" :placement="placement">
      <slot v-if="$slots.default" />
      <div ref="textRef" class="auto-tooltip-text" v-else>{{ data }}</div>
    </el-tooltip>
  </div>
</template>
<script setup lang="ts">
const { proxy } = getCurrentInstance() as any;
//获取父级数据
const props = withDefaults(
  defineProps<{
    placement?: string;
    data?: string;// 必须传入的文本内容
    maxLength?: number;// 可选参数：手动控制截断长度（默认不生效，仅用于某些场景）
    height?: number;// 
  }>(),
  {
    placement: 'top',
    data: '--',
    height: 32,
  },
);
watch(() => props.data, () => {
  checkOverflow()
});
const container = ref<HTMLSpanElement | null>(null)
const textRef = ref<HTMLSpanElement | null>(null)
const showTooltip = ref(true)

// 判断是否溢出
const checkOverflow = () => {
  if (!!!props.data && !proxy.$slots.default) return
  setTimeout(() => {
    if (!textRef.value || !container.value) return
    const textWidth = textRef.value.scrollWidth
    const containerWidth = container.value.clientWidth
    showTooltip.value = textWidth > containerWidth
  }, 300)
}
//窗口变化
proxy.$useResize(() => {
  checkOverflow()
})
</script>
<style scoped>
.auto-tooltip-container {
  display: flex;
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.auto-tooltip-text {
  display: block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
